package com.fileupload.fileupload.handler;

import com.fileupload.fileupload.utils.WsSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;

@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {

    private WebSocketSession session;

    /**
     * 连接建立后
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("连接建立：" + session.getId());
        this.session = session; // 保存会话对象
        WsSessionManager.add(session.getId(), session);
    }

    /**
     * 关闭连接后
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("连接关闭：" + session.getId());
        WsSessionManager.remove(session.getId());
    }

    /**
     * 收到文本消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("收到消息：" + payload);
        session.sendMessage(new TextMessage("收到消息：" + payload));
    }

    // 向客户端发送消息的方法
    public void sendMessageToClient(String message) throws IOException {

        if (getSession() != null && getSession().isOpen()) {
            getSession().sendMessage(new TextMessage(message));
        }

    }

    // 获取当前会话
    protected WebSocketSession getSession() {
        return this.session ; // 保存会话对象;
    }

    /**
     * 是否支持部分消息
     * @return
     */
    @Override
    public boolean supportsPartialMessages() {
        return super.supportsPartialMessages();
    }

    /**
     * 连接出现异常
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    /**
     * 收到Pong消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
    }

    /**
     * 收到二进制消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
    }
}
